/*
 * Copyright (c) 2025 CAX Conversion Project
 */
package com.comac.ins.isfd.util;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.json.utils.JsonUtils;
import com.comac.ins.isfd.domain.vo.MapFieldsVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.*;

@Slf4j
public class ExcelUtils {

    public static final String TEMP_DIR = "tempDir";

    public static Map<String, File> splitExcelBySheet(MultipartFile file, String mapFields) {
        Map<String, File> sheetFiles = new HashMap<>();
        File tempDir = null;
        try {
            // 创建一个临时文件夹来存储文件
            tempDir = Files.createTempDirectory(TEMP_DIR).toFile();
        } catch (Exception e) {
            log.error("创建临时目录失败", e);
            throw new BaseException("创建临时目录失败");
        }

        try (InputStream is = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(is)) {

            JSONObject mapFieldsJson = JSONUtil.parseObj(mapFields);
            Set<String> keys = mapFieldsJson.keySet();

            for (Sheet sheet : workbook) {
                String sheetName = sheet.getSheetName();

                Optional<String> optional = keys.stream().filter(k -> k.contains(sheetName)).findFirst();
                if (optional.isEmpty()) {
//                    log.error("映射的sheetName和实际的sheetName不匹配，请确认后重试！");
//                    throw new BaseException("映射的sheetName和实际的sheetName不匹配，请确认后重试！");
                    continue;
                }
                String key = optional.get();
                // 修改表头
                List<MapFieldsVo> mapFieldsVoList = JsonUtils.parseArray(mapFieldsJson.getStr(key), MapFieldsVo.class);
                String[] sheetNameAndTableName = key.split("::");
                String tableName = sheetNameAndTableName[1];

                // 创建新的Excel工作簿和Sheet
                Workbook newWorkbook = new XSSFWorkbook();
                Sheet newSheet = newWorkbook.createSheet(sheetName);

                // 特别处理第一行
                Row firstRow = sheet.getRow(0); // 获取第一行
                if (firstRow != null) {
                    Row newFirstRow = newSheet.createRow(0); // 在新Sheet中创建第一行
                    // 假设我们仅复制值，不改变单元格类型
                    for (Cell cell : firstRow) {
                        Cell newCell = newFirstRow.createCell(cell.getColumnIndex(), cell.getCellType());
                        String stringCellValue = cell.getStringCellValue();
                        Optional<MapFieldsVo> first = mapFieldsVoList.stream().filter(mapFieldsVo -> stringCellValue.equals(mapFieldsVo.getMetadataField())).findFirst();
                        if (first.isPresent()) {
                            MapFieldsVo mapFieldsVo = first.get();
                            newCell.setCellValue(mapFieldsVo.getTargetField());
                        } else {
                            newCell.setCellValue(cell.getStringCellValue());
                        }
                    }
                }

                // 复制剩余的行（从第二行开始）
                for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                    Row row = sheet.getRow(rowNum);
                    if (row != null) {
                        Row newRow = newSheet.createRow(rowNum);
                        for (Cell cell : row) {
                            Cell newCell = newRow.createCell(cell.getColumnIndex(), cell.getCellType());
                            switch (cell.getCellType()) {
                                case STRING:
                                    newCell.setCellValue(cell.getStringCellValue());
                                    break;
                                case NUMERIC:
                                    newCell.setCellValue(cell.getNumericCellValue());
                                    break;
                                case FORMULA:
                                    newCell.setCellValue(cell.getNumericCellValue());
                                    break;
                                default:
                                    newCell.setCellValue(cell.getStringCellValue());
                                    break;
                                // 处理其他类型...
                            }
                        }
                    }
                }

                // 将新工作簿写入临时文件
                File tempFile = new File(tempDir, sheetName + ".xlsx");
                try (OutputStream os = new FileOutputStream(tempFile)) {
                    newWorkbook.write(os);
                }

                // 将sheetName::tableName名称和文件添加到map中
                sheetFiles.put(sheetName + "::" + tableName, tempFile);
            }
        } catch (Exception e) {
            log.error("excel拆解为sheet文件失败", e);
            throw new BaseException("excel拆解为sheet文件失败");
        }

        return sheetFiles;
    }

}
